"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 防篡改
Case Name   : 创建auditadmin用户验证全局临时表权限组合的情况下，功能正常
Create At   : 2022/3/15
Owner       : opentestcase012
Description :
    1.设置参数并重启数据库enableseparationofduty=on
    2.创建普通用户和auditadmin用户
    3.普通用户连接,创建全局临时表
    4.auditadmin用户连接,对表进行增删改查清空操作
    5.普通用户连接,给auditadmin用户授权
    6.auditadmin用户连接,对表进行增删改查清空操作
    7.清理环境
Expect      :
    1.成功
    2.成功
    3.成功
    4.对表操作失败
    5.成功
    6.对表操作成功
    7.清理环境成功
History     :
"""

import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import macro


class Security(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.common = Common()
        self.u_name = 'u_security_combineprivilege_0018'
        self.u_name_01 = 'u_security_combineprivilege_0018_01'
        self.t_name = 't_security_combineprivilege_0018'
        self.default_value1 = self.common.show_param('enableSeparationOfDuty')

    def test_security(self):
        text = '-----step1：设置参数并重启数据库enableSeparationOfDuty=on; ' \
               'expect:成功-----'
        self.log.info(text)
        mod_msg = self.pri_sh.execute_gsguc('set',
                                            self.constant.GSGUC_SUCCESS_MSG,
                                            'enableSeparationOfDuty=on')
        self.assertTrue(mod_msg, '执行失败:' + text)
        result = self.pri_sh.restart_db_cluster()
        self.assertTrue(result, '执行失败' + text)

        text2 = '-----step2：创建普通用户和auditadmin用户 expect:成功-----'
        self.log.info(text)
        sql_1 = f"drop user if exists {self.u_name}," \
            f"{self.u_name_01} cascade; " \
            f"create user {self.u_name} password '{macro.COMMON_PASSWD}';" \
            f"create user {self.u_name_01} auditadmin password " \
            f"'{macro.COMMON_PASSWD}';"
        self.log.info(sql_1)

        text3 = '-----step3：普通用户连接,创建全局临时表 expect:成功-----'
        self.log.info(text)
        sql_2 = f"set role {self.u_name} password '{macro.COMMON_PASSWD}';" \
            f"drop table if exists {self.t_name};" \
            f"create temp table {self.t_name}" \
            f"(id int primary key,name varchar(100));" \
            f"reset role;"
        self.log.info(sql_2)

        text4 = '-----step4：auditadmin用户连接,对表进行增删改查清空操作; expect:对表操作失败-----'
        self.log.info(text)
        sql_3 = f"set role {self.u_name_01} password " \
            f"'{macro.COMMON_PASSWD}';" \
            f"insert into {self.t_name} " \
            f"values(1,'beijing'),(2,'shanghai');" \
            f"select * from {self.t_name};" \
            f"update {self.t_name} set name='shanxi' " \
            f"where id=2;" \
            f"delete from {self.t_name} where id=2;" \
            f"truncate table {self.t_name};" \
            f"reset role;"
        self.log.info(sql_3)

        text5 = '-----step5：普通用户连接,给auditadmin用户授权; expect:成功-----'
        self.log.info(text)
        sql_4 = f"set role {self.u_name} password '{macro.COMMON_PASSWD}';" \
            f"grant usage on schema {self.u_name} " \
            f"to {self.u_name_01};" \
            f"grant select,insert,update,delete,truncate on table " \
            f"{self.t_name} to {self.u_name_01};" \
            f"reset role;"
        self.log.info(sql_4)

        text6 = '-----step6：auditadmin用户连接,对表进行增删改查清空操作; expect:成功-----'
        self.log.info(text)
        sql_5 = f"set role {self.u_name_01} " \
            f"password '{macro.COMMON_PASSWD}';" \
            f"insert into {self.t_name} " \
            f"values(1,'beijing'),(2,'shanghai');" \
            f"select * from {self.t_name};" \
            f"update {self.t_name} set name='shanxi' " \
            f"where id=2;" \
            f"delete from {self.t_name} where id=2;" \
            f"truncate table {self.t_name};" \
            f"reset role;"
        self.log.info(sql_5)

        text = '-----执行sql语句-----'
        self.log.info(text)
        sql_cmd = f'{sql_1}{sql_2}{sql_3}{sql_4}{sql_5}'
        msg = self.pri_sh.execut_db_sql(sql_cmd)
        self.log.info(msg)
        self.assertIn(self.constant.DROP_ROLE_SUCCESS_MSG, msg,
                      '执行失败:' + text2)
        self.assertEqual(2, msg.count(self.constant.CREATE_ROLE_SUCCESS_MSG),
                         '执行失败:' + text2)
        self.assertIn(self.constant.DROP_TABLE_SUCCESS, msg, '执行失败:' + text3)
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS, msg,
                      '执行失败:' + text3)
        self.assertEqual(5, msg.count(
            f'permission denied for relation {self.t_name}'), '执行失败:' + text4)
        self.assertEqual(2, msg.count(self.constant.GRANT_SUCCESS_MSG),
                         '执行失败:' + text5)
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, msg, '执行失败:' + text6)
        self.assertIn(self.constant.UPDATE_SUCCESS_MSG, msg, '执行失败:' + text6)
        self.assertIn(self.constant.DELETE_SUCCESS_MSG, msg, '执行失败:' + text6)
        self.assertIn(self.constant.TRUNCATE_SUCCESS_MSG, msg,
                      '执行失败:' + text6)
        self.assertIn('2 rows', msg, '执行失败:' + text6)

    def tearDown(self):
        self.log.info('-----step7：清理环境-----')
        text1 = '-----删除用户 expect:成功-----'
        self.log.info(text1)
        drop_cmd = f"drop user if exists {self.u_name}," \
            f"{self.u_name_01} cascade;"
        drop_msg = self.pri_sh.execut_db_sql(drop_cmd)
        self.log.info(drop_msg)

        text2 = '-----修改参数enableSeparationOfDuty为初始值 expect:成功-----'
        self.log.info(text2)
        mod_msg1 = self.pri_sh.execute_gsguc('set',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             f'enableSeparationOfDuty='
                                             f'{self.default_value1}')
        restart_res = self.pri_sh.restart_db_cluster()

        self.log.info('-----断言tearDown执行成功-----')
        self.assertIn(self.constant.DROP_ROLE_SUCCESS_MSG, drop_msg,
                      '执行失败:' + text1)
        self.assertTrue(mod_msg1, '执行失败:' + text2)
        self.assertTrue(restart_res, '执行失败:' + text2)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
